/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */

var buildTree = function (preorder, inorder) {
    let len = preorder.length
    let root = build(0, len - 1, 0, len - 1)
    function build(preL, preR, inL, inR) {
        if (preL > preR) {
            return null
        }
        let root = new TreeNode()
        root.val = preorder[preL]
        let k = inorder.indexOf(preorder[preL])
        let numLeft = k - inL
        root.left = build(preL + 1, preL + numLeft, inL, k - 1)
        root.right = build(preL + numLeft + 1, preR, k + 1, inR)
        return root
    }
    return root
};